/* 
订单控制层
*/
const { dbsql } = require('../model/model')

// 提交订单
exports.doAddOrder = (req, res) => {
  let { recipient, phone, address, totalprice, books } = req.body
  
  // 检查是否有用户信息
  if (!req.data || !req.data.u_id) {
    return res.status(401).send({ code: 401, message: '请先登录', data: null });
  }
  
  let u_id = req.data.u_id;
  
  // 检查必要的参数
  if (!recipient || !phone || !address || !books || !Array.isArray(books) || books.length === 0) {
    return res.status(400).send({ code: 400, message: '订单信息不完整', data: null });
  }
  
  // 1.插入订单表数据-->拿到order_id
  let sql = `INSERT INTO orders(u_id,recipient,address,phone,totalprice)VALUES(?,?,?,?,?);`
  dbsql(sql, [u_id, recipient, address, phone, totalprice], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '新增订单失败' + err.message, data: null })
    }
    let order_id = results.insertId
    // 2.插入订单详情（选中几个商品对应插入几条数据）
    books.forEach(item => {
      let sql2 = `INSERT INTO order_details VALUES (NULL,?,?,?);`
      dbsql(sql2, [order_id,item.b_id,item.num], (err2, results2) => {
        if (err2) {
          return res.send({ code: 101, message: '新增订单详情失败' + err2.message, data: null })
        }
        // 3.减少商品表对应数据库存
        let sql3 = `UPDATE book SET stock=stock-? WHERE b_id=?;`
        dbsql(sql3, [item.num, item.b_id], (err3, results3) => {
          if (err3) {
            return res.send({code:101,message:'更新库存失败'+err3.message,data:null})
          }
          // 4.删除购物车对应数据
          let sql4 = `DELETE FROM shopcart WHERE cart_id=?;`
          dbsql(sql4, [item.cart_id], (err4, results4) => {
            if (err4) {
              return res.send({ code: 101, message: '删除购物车失败' + err4.message, data: null })
            }
          })
        })
      })
    })
    res.send({ code: 200, message: '恭喜你，下单成功', data: null })
  })
}

// 展示订单
exports.showOrders = (req, res) => {
  // 检查是否有用户信息
  if (!req.data || !req.data.u_id) {
    return res.status(401).send({ code: 401, message: '请先登录', data: null });
  }
  
  const u_id = req.data.u_id;
  
  let sql =`SELECT * FROM orders WHERE u_id=?;
SELECT order_details.*,price,img,bookname as booksname FROM order_details JOIN book ON order_details.b_id=book.b_id;`
  dbsql(sql, [u_id], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '获取订单失败: ' + err.message, data: null });
    }
    // 处理数据格式  [{recipient:'xx',...,books:[]}]
    // 订单信息  results[0]  详情信息  results[1]
    let orders = results[0].map(item => {
      let books = results[1].filter(value => {
        return value.order_id == item.order_id;
      });
      
      // 格式化订单日期
      const orderDate = item.orderDate ? new Date(item.orderDate).toISOString() : null;
      
      return {
        ...item,
        orderDate,
        books: books
      };
    });
    
    res.send({code: 200, message: '获取订单成功', data: orders});
  });
}

// 删除订单
exports.deleteOrder = (req, res) => {
  const { id } = req.params;
  
  // 检查是否有用户信息
  if (!req.data || !req.data.u_id) {
    return res.status(401).send({ code: 401, message: '请先登录', data: null });
  }
  
  const u_id = req.data.u_id;
  
  // 先检查订单是否属于该用户
  const checkSql = `SELECT * FROM orders WHERE order_id = ? AND u_id = ?`;
  dbsql(checkSql, [id, u_id], (checkErr, checkResults) => {
    if (checkErr) {
      return res.send({ code: 101, message: '查询订单失败: ' + checkErr.message, data: null });
    }
    
    if (checkResults.length === 0) {
      return res.send({ code: 403, message: '无权删除此订单或订单不存在', data: null });
    }
    
    // 先删除订单详情
    const detailsSql = `DELETE FROM order_details WHERE order_id = ?`;
    dbsql(detailsSql, [id], (detailsErr) => {
      if (detailsErr) {
        return res.send({ code: 101, message: '删除订单详情失败: ' + detailsErr.message, data: null });
      }
      
      // 再删除订单主表
      const orderSql = `DELETE FROM orders WHERE order_id = ?`;
      dbsql(orderSql, [id], (orderErr, orderResults) => {
        if (orderErr) {
          return res.send({ code: 101, message: '删除订单失败: ' + orderErr.message, data: null });
        }
        
        res.send({ code: 200, message: '订单删除成功', data: null });
      });
    });
  });
};

// ===== 后台管理API =====

// 获取所有订单列表（后台管理）
exports.adminGetAllOrders = (req, res) => {
  // 检查是否是管理员
  if (!req.data || !req.data.isAdmin) {
    return res.status(403).send({ code: 403, message: '无权访问', data: null });
  }
  
  const sql = `
    SELECT o.*, u.username 
    FROM orders o 
    JOIN users u ON o.u_id = u.u_id 
    ORDER BY o.orderDate DESC;
    
    SELECT od.*, b.bookname, b.price, b.img 
    FROM order_details od 
    JOIN book b ON od.b_id = b.b_id;
  `;
  
  dbsql(sql, [], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '获取订单列表失败: ' + err.message, data: null });
    }
    
    // 处理数据格式
    const orders = results[0].map(order => {
      const books = results[1].filter(detail => detail.order_id === order.order_id);
      
      // 计算订单中的图书总数
      const bookCount = books.reduce((total, book) => total + book.num, 0);
      
      return {
        ...order,
        books,
        bookCount
      };
    });
    
    res.send({ code: 200, message: '获取订单列表成功', data: orders });
  });
};

// 获取订单详情（后台管理）
exports.adminGetOrderDetail = (req, res) => {
  // 检查是否是管理员
  if (!req.data || !req.data.isAdmin) {
    return res.status(403).send({ code: 403, message: '无权访问', data: null });
  }
  
  const { id } = req.params;
  
  const sql = `
    SELECT o.*, u.username 
    FROM orders o 
    JOIN users u ON o.u_id = u.u_id 
    WHERE o.order_id = ?;
    
    SELECT od.*, b.bookname, b.price, b.img 
    FROM order_details od 
    JOIN book b ON od.b_id = b.b_id 
    WHERE od.order_id = ?;
  `;
  
  dbsql(sql, [id, id], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '获取订单详情失败: ' + err.message, data: null });
    }
    
    if (results[0].length === 0) {
      return res.send({ code: 404, message: '订单不存在', data: null });
    }
    
    const order = results[0][0];
    const books = results[1];
    
    const orderDetail = {
      ...order,
      books
    };
    
    res.send({ code: 200, message: '获取订单详情成功', data: orderDetail });
  });
};

// 订单发货（后台管理）
exports.adminShipOrder = (req, res) => {
  // 检查是否是管理员
  if (!req.data || !req.data.isAdmin) {
    return res.status(403).send({ code: 403, message: '无权访问', data: null });
  }
  
  const { orderId, expressCompany, trackingNumber } = req.body;
  
  if (!orderId || !expressCompany || !trackingNumber) {
    return res.status(400).send({ code: 400, message: '发货信息不完整', data: null });
  }
  
  const shippingTime = new Date();
  
  const sql = `
    UPDATE orders 
    SET status = '1', 
        expressCompany = ?, 
        trackingNumber = ?, 
        shippingTime = ? 
    WHERE order_id = ? AND status = '0'
  `;
  
  dbsql(sql, [expressCompany, trackingNumber, shippingTime, orderId], (err, result) => {
    if (err) {
      return res.send({ code: 101, message: '订单发货失败: ' + err.message, data: null });
    }
    
    if (result.affectedRows === 0) {
      return res.send({ code: 400, message: '订单不存在或已发货/取消', data: null });
    }
    
    res.send({ code: 200, message: '订单发货成功', data: null });
  });
};

// 取消订单（后台管理）
exports.adminCancelOrder = (req, res) => {
  // 检查是否是管理员
  if (!req.data || !req.data.isAdmin) {
    return res.status(403).send({ code: 403, message: '无权访问', data: null });
  }
  
  const { id } = req.params;
  
  const sql = `
    UPDATE orders 
    SET status = '2' 
    WHERE order_id = ? AND status = '0'
  `;
  
  dbsql(sql, [id], (err, result) => {
    if (err) {
      return res.send({ code: 101, message: '取消订单失败: ' + err.message, data: null });
    }
    
    if (result.affectedRows === 0) {
      return res.send({ code: 400, message: '订单不存在或已发货/取消', data: null });
    }
    
    // 恢复库存
    const getDetailsSql = `
      SELECT * FROM order_details WHERE order_id = ?
    `;
    
    dbsql(getDetailsSql, [id], (detailsErr, details) => {
      if (detailsErr) {
        return res.send({ code: 200, message: '订单已取消，但恢复库存失败', data: null });
      }
      
      // 逐个恢复商品库存
      details.forEach(item => {
        const updateStockSql = `
          UPDATE book SET stock = stock + ? WHERE b_id = ?
        `;
        
        dbsql(updateStockSql, [item.num, item.b_id], (stockErr) => {
          if (stockErr) {
            console.error('恢复库存失败:', stockErr);
          }
        });
      });
      
      res.send({ code: 200, message: '订单取消成功', data: null });
    });
  });
};

// 获取订单统计数据（后台管理）
exports.adminGetOrderStats = (req, res) => {
  // 检查是否是管理员
  if (!req.data || !req.data.isAdmin) {
    return res.status(403).send({ code: 403, message: '无权访问', data: null });
  }
  
  const sql = `
    SELECT 
      COUNT(*) as totalOrders,
      SUM(CASE WHEN status = '0' THEN 1 ELSE 0 END) as pendingOrders,
      SUM(CASE WHEN status = '1' THEN 1 ELSE 0 END) as shippedOrders,
      SUM(CASE WHEN status = '2' THEN 1 ELSE 0 END) as canceledOrders,
      SUM(totalprice) as totalSales
    FROM orders;
    
    SELECT 
      DATE_FORMAT(orderDate, '%Y-%m-%d') as date,
      COUNT(*) as orderCount,
      SUM(totalprice) as dailySales
    FROM orders
    WHERE orderDate >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY DATE_FORMAT(orderDate, '%Y-%m-%d')
    ORDER BY date;
  `;
  
  dbsql(sql, [], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '获取订单统计失败: ' + err.message, data: null });
    }
    
    const stats = results[0][0];
    const dailyStats = results[1];
    
    res.send({ 
      code: 200, 
      message: '获取订单统计成功', 
      data: {
        stats,
        dailyStats
      } 
    });
  });
};
